<html class="bluetoothvideoClass"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sidianneng</title>
</head>
<body>
<script>

var connectTrys = 0;

//BLE value
var bluetoothDevice, gattServer, Theservice, writeCharacteristic;
var ServiceMain;
var settingsCharacteristics;

function connect() {
    var deviceOptions = {
		optionalServices: [0x00ff],
        acceptAllDevices: true,
    }; 

    console.log(deviceOptions)
	
	if (bluetoothDevice != null) bluetoothDevice.gatt.disconnect();
	
	gattServer = null;
	Theservice = null;
	writeCharacteristic = null;
	settingsCharacteristics = null;
	
    navigator.bluetooth.requestDevice(deviceOptions).then(device => {
        bluetoothDevice = device;
        addLog("Connecting to: " + bluetoothDevice.name);
		bluetoothDevice.gatt.connect().then(server => {
			console.log("Found GATT server");
			gattServer = server;
			return gattServer.getPrimaryService(0x00ff);
		}).then(service => {
			console.log("Found service");
			Theservice = service;
			return Theservice.getCharacteristic(0xff01);
		}).then(characteristic => {
			console.log("Found write characteristic");
			settingsCharacteristics = characteristic;
			return settingsCharacteristics.startNotifications();
		}).then(() => {
			console.log("Notifications started");
			settingsCharacteristics.addEventListener('characteristicvaluechanged', handleNotifications);
		}).catch(handleError);
		
    }).catch(handleError);
}

let hexArray = [];
let imageUrl = null;

function handleNotifications(event) {
    let value = event.target.value;

    for (let i = 6; i < value.byteLength; i++) {
        let hexString = value.getUint8(i).toString(16).padStart(2, '0');
        hexArray.push(hexString);
    }

    if (value.getUint8(2) == value.getUint8(3)) {
        console.log('Received complete image data');

        let byteArray = new Uint8Array(hexArray.map(byte => parseInt(byte, 16)));

		// convert Uint8Array to Base64
        let binary = '';
        for (let i = 0; i < byteArray.byteLength; i++) {
            binary += String.fromCharCode(byteArray[i]);
        }
        let base64String = window.btoa(binary);

		// update the src of image
        let img = document.getElementById('imageDisplay');
        img.src = `data:image/jpeg;base64,${base64String}`;

        hexArray = [];
    }
}

function disconnect() {
    if (bluetoothDevice) {
        if (bluetoothDevice.gatt.connected) {
            bluetoothDevice.gatt.disconnect();
            addLog('Disconnected from: ' + bluetoothDevice.name);
        } else {
            addLog('Device already disconnected.');
        }
    } else {
        addLog('No device to disconnect.');
    }
}

function hexToBytes(hex) {
    for (var bytes = [], c = 0; c < hex.length; c += 2)
        bytes.push(parseInt(hex.substr(c, 2), 16));
    return new Uint8Array(bytes);
}

function senddata(data, characteristic){
    return new Promise(function(resolve, reject) {
        console.log("Send: " + data);
        characteristic.writeValue(hexToBytes(data)).then(function(character) {
            resolve("ok");
        }).catch(function(err) {
            reject("some error while sending char data");
        });
    });
}

function write_data() {		
	var bytes_to_send = "dd";
	addLog("Sending bytes: " + bytes_to_send);
	senddata(bytes_to_send, settingsCharacteristics);
}

function read_data() {
	return settingsCharacteristics.readValue().then(value => {
        let data = new Uint8Array(value.buffer);
        console.log("Read value:", data);
        let hexString = Array.from(data).map(byte => byte.toString(16).padStart(2, '0')).join(' ');
        console.log("Read value (hex):", hexString);
    });
}

function addLog(logTXT) {
    var time = new Date().toLocaleTimeString("de-DE");
    var logString = time + ": " + logTXT;
    document.getElementById("log").innerHTML += logString + "<br>";
}

function handleError(error) {
    addLog(error);
    if (connectTrys < 5) {
        connectTrys++;
        addLog("Reconnect " + connectTrys + " from " + 5);
    } else {
        addLog("Something went wrong, to many reconnect's");
        connectTrys = 0;
    }
}
</script>
<big><big>Bluetooth Video Transmission</big></big><br>
  <button type="button" onclick="connect();">Connect</button>
  <button type="button" onclick="disconnect();">Disconnect</button><br><br>
  <button type="button" onclick="write_data();">Write_Data</button>
  <button type="button" onclick="read_data();">Read_Data</button><br><br>
  <img id="imageDisplay" alt="Received Image" /><br><br>
  <div id="log">Log:<br></div>
  <div id="result"></div>
</body></html>
